import React, { useEffect, useState } from "react";
import "../../css/Ranking.less";
import RankingItem from "./component/RankingItem";
import { List } from "react-vant";
import instance from "../utils/https";
import Position from "../../components/Position";
import Slideshow from "../../components/Slideshow";
import Presentation from "../../components/Presentation";
import FloatingBall from "../../components/FloatingBall";
import Text_Carousel from "../../components/Text_Carousel";
import { useSelector, useDispatch } from "react-redux";
import { setRankingPageP_id } from "../../store/modules/data";

interface RankingItemType {
  _id: string;
  mark: number;
  name: string;
  vote: number;
  avtor: string;
}

const Ranking: React.FC = () => {
  const [pageNumber, setPageNumber] = useState(1);
  const [topThree, setTopThree] = useState<RankingItemType[]>([]);
  const [rankingList, setRankingList] = useState<RankingItemType[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [activityList, setActivityList] = useState<null>(null);
  let rankingPageP_id = useSelector((state: any) => state.rankingPageP_id);
  const dispatch = useDispatch();

  const fillTopThree = (userRank: any[]) => {
    return [...userRank]
      .concat(Array(3 - userRank.length).fill(null))
      .slice(0, 3);
  };

  const getActivityInfo = async () => {
    try {
      const res: any = await instance.get("/homePage/getVisit");
      setActivityList(res.data || null); // 假设只使用第一个活动
    } catch (error) {
      console.error("获取活动信息失败", error);
    }
  };

  useEffect(() => {
    getActivityInfo();
  }, []);

  useEffect(() => {
    fetchRankingData(true); // 首次加载时传递 true 来指示是否需要重置数据
  }, [rankingPageP_id]);

  const handlePositionChange = () => {
    fetchRankingData(true); // 位置变化时也传递 true 来指示需要重置数据
  };

  const fetchRankingData = async (reset = false) => {
    if (reset) {
      setPageNumber(1); // 重置页码
      setRankingList([]); // 清空排名列表
      setTopThree([]); // 清空 topThree
    }
    try {

      if (rankingPageP_id === 1) {
        rankingPageP_id = "";
      }

      const res: any = await instance.get(
        `/rank/getRank?page=${pageNumber}&pagesize=6&position=${rankingPageP_id}`
      );
      if (res.code === 200) {
        setTopThree(res.userRank.slice(0, 3));
        setRankingList((prev) =>
          reset ? res.userRanks : [...prev, ...res.userRanks]
        );
        setTotalCount(res.total);
        setPageNumber(reset ? 1 : pageNumber + 1);
      } else {
        console.error("获取排名数据失败", res.code);
      }
    } catch (err) {
      console.error("获取排名数据失败", err);
    }
  };

  const getRankClass = (index: number): string =>
    ["second-place", "first-place", "third-place"][index] || "";

  return (
    <div className="ranking">
      <Text_Carousel activityList={activityList} />
      <FloatingBall />
      <Slideshow />

      <div className="Ranking_Three">
        {topThree.length === 0 ? (
          // 如果没有前三名数据，显示提示文字
          <div className="empty-ranking">
            暂时没有排名数据，稍后再来查看吧！
          </div>
        ) : (
          fillTopThree(topThree).map((item, index) => (
            <div
              key={index}
              className={`rank-item ${getRankClass(index)} ${
                item ? "show" : ""
              }`}
            >
              {item ? (
                <>
                  <img
                    className="rank-circle"
                    src={item.avtor}
                    alt={`${item.name}'s avatar`}
                  />
                  <span className="name">{item.name}</span>
                  <span className="votes">票数：{item.vote}</span>
                </>
              ) : (
                <div style={{ textAlign: "center" }}>此位置空缺</div>
              )}
            </div>
          ))
        )}
      </div>

      <div className="con">
        <Presentation activityList={activityList} />
        <Position
          pId={rankingPageP_id}
          setPId={(id: any) => dispatch(setRankingPageP_id(id))}
          onSearch={handlePositionChange}
        />
        <div className="p_Ranking">选手排名</div>
      </div>

      <List
        className="content"
        finished={rankingList.length >= totalCount - 3}
        finishedText="没有更多了"
        onLoad={() => fetchRankingData()}
        offset={0}
      >
        {rankingList.map((item, index) => (
          <RankingItem
            key={item._id}
            Serial_Number={item.mark}
            name={item.name}
            Votes={item.vote}
            rank={index + 4}
            avtor={item.avtor}
          />
        ))}
      </List>

      <div style={{ height: "60px" }}></div>
    </div>
  );
};

export default Ranking;
